<template>
  <PageWrapper dense contentFullHeight class="flex">
    <div :class="prefixCls" class="relative w-full h-full">
      <Spin :spinning="loading" wrapperClassName="h-full basic-model-spin  ">
        <BasicTable
          @fetch-success="handleGoToFlow"
          @register="registerTable"
          @change="handleChangeSearch"
          v-show="!flowDetailVisible"
        >
          <template #tableTitle v-if="isShowTop">
            <div class="flex flex-1 items-center justify-between">
              <template v-for="(btns, _) in tableItems" :key="_">
                <ButtonActions
                  :tableFn="tableFn"
                  @add="handleAddFn"
                  @flow-add="handleFlowAddFn"
                  @flow-handround="handleFlowComFn"
                  @flow-consult="handleFlowComFn"
                  @flow-turnbatch="handleFlowComFn"
                  @flow-handround-delete="
                    () => {
                      handleBatchDel(DelBatchType.FLOWHANDROUNDDELETE, comParams, tableFn);
                    }
                  "
                  @flow-delete="
                    () => {
                      handleBatchDel(DelBatchType.FLOWDELETE, comParams, tableFn);
                    }
                  "
                  @flow-renovate="flowRenovateHandler"
                  @flow-revocation="flowRevocationHandler"
                  :data="btns"
                />
              </template>
            </div>
          </template>
          <template #bodyCell="data">
            <template v-if="data.column.key === 'rightAction'">
              <TableAction :record="data.record" :actionsFn="actionsFn" />
            </template>
          </template>
        </BasicTable>
      </Spin>

      <!-- 流程申请，审核，详情页面 -->
      <FlowDetail
        v-model:visible="flowDetailVisible"
        @success="handleSuccess"
        ref="flowDetail"
        :node-disabled="true"
      />

      <!-- 流程修复页面 -->
      <FlowRenovatePage
        v-model:visible="flowRenovatePageVisible"
        :workItemId="workItemId"
        @success="handleSuccess"
      />
    </div>
  </PageWrapper>
  <FormModal @register="registerModal" @success="handleSuccess" />
  <FormDrawer @register="registerDrawer" @success="handleSuccess" />
  <ModelDesign :classify="classify" :modelId="modelId" @success="init" />
  <FlowListModel @register="registerFlowModel" @success="openFlowListSuccess" />

  <!-- 传阅，征询，转批 -->
  <ComFlowModel
    :formScheama="formScheama"
    @register="registerComFlowModel"
    @success="handleSuccess"
  />
</template>

<script lang="ts" setup>
  import { ref, unref, computed, onMounted, inject, watch } from 'vue';
  import { PageWrapper } from '/@/components/Page';
  import FormDrawer from '/@/components/ModelTable/src/components/FormDrawer.vue';
  import FormModal from '/@/components/ModelTable/src/components/FormModal.vue';
  import ModelDesign from '/@/components/ModelTable/src/components/ShowModelDesign.vue';

  import {
    BasicTable,
    useTable,
    TableAction,
    ActionItem,
    FormProps,
    TableRowSelection,
  } from '/@/components/Table';
  import { Spin } from 'ant-design-vue';

  // import { Icon } from '/@/components/Icon';
  import { useDrawer } from '/@/components/Drawer';
  import { useModal } from '/@/components/Modal';

  import { useRouter } from 'vue-router';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { useActions } from '/@/components/ModelTable/src/hooks/useActions';
  // import { useDebounceFn } from '@vueuse/core';
  import { useUserStore } from '/@/store/modules/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getCSSValue } from '/@/utils';

  import getColumn from '/@/components/ModelTable/src/hooks/setColumn';
  import {
    beforeFetch,
    useSearchForm,
    handleSearchInfoFn,
  } from '/@/components/ModelTable/src/hooks/useTableSearch';
  import {
    BTN_POSITION,
    DIALOG_TYPE,
    BTN_EVENT_TYPE,
  } from '/@/views/config-center/model-design/model';

  import ButtonActions from '/@/components/ModelTable/src/components/ButtonActions.vue';
  import FlowDetail from './components/FlowDetail.vue';

  import {
    getModuleListInfoApi,
    getGetModuleCommonListApi,
    saveUserProfileApi,
  } from '/@/api/config-center/model-design';
  import FlowListModel from './components/FlowListModel.vue';
  import { getRowKeys } from '/@/components/ModelTable/src/hooks/functionSet';
  import { useFlowStoreWithout } from '/@/store/modules/flow';

  import ComFlowModel from './components/ComFlowModel.vue';

  import { checkFlowFn } from './helper';

  import {
    handleBatchDel,
    getBtnFormScheama,
    getSelectRowsFn,
    getRecallWorkItemFn,
  } from './helper';
  import { DelBatchType } from './types/index';

  import FlowRenovatePage from './components/renovate/index.vue';

  const flowStore = useFlowStoreWithout();

  const loading = ref(true);
  const { prefixCls } = useDesign('TableModel');

  let btnItemTemp;

  interface ModalParams {
    moduleId?: string;
    modelId?: string;
  }

  const props = withDefaults(
    defineProps<{
      modalParams?: ModalParams;
    }>(),
    {
      modalParams: () => ({}),
    },
  );

  // eslint-disable-next-line vue/no-setup-props-destructure
  const { modalParams } = props;

  const userStore = useUserStore();
  const { createMessage } = useMessage();

  const router = useRouter();
  const { currentRoute } = router;
  const route = unref(currentRoute);

  const moduleId = modalParams.moduleId || (route.meta.moduleId as string);
  const modelId = modalParams.modelId || (route.meta.modelId as string);
  const query = (route.meta.query as Indexable) || {};
  const modelInfo = ref();

  const flowDetailVisible = ref<boolean>(false);
  const flowDetail = ref();

  const formScheama = ref();

  const flowRenovatePageVisible = ref(false);
  const workItemId = ref();

  let setComponentName = inject('setComponentName') as Fn;
  setComponentName('Module' + moduleId);
  const classify = ref(1);
  // const record = ref<Indexable>({});

  const [registerTable, tableFn] = useTable({
    useSearchForm: false,
    showTableSetting: false,
    bordered: false,
    showIndexColumn: false,
  });

  const {
    reload,
    setLoading,
    setProps,
    getDataSource,
    getSelectRows,
    clearSelectedRowKeys,
    //  setTableData
  } = tableFn;

  const comParams = computed(() => {
    return {
      moduleId: unref(moduleId),
      tableModelId: unref(modelId),
      primaryKey: modelInfo.value.primaryKey,
      complexParams: query,
    };
  });

  // 消息跳转
  function handleGoToFlow(_, flowDataQuery) {
    const flowData = flowStore.getFlowParams;

    let workItemId;

    if (flowData) {
      workItemId = flowData.workItemId;
    }

    console.log('query2', typeof flowData, workItemId, flowData);

    if (flowDataQuery) {
      workItemId = flowDataQuery.workItemId;
    }
    if (workItemId) {
      try {
        const list = getDataSource();

        if (list.length) {
          const record = list.find((item) => item.WorkItemID == workItemId) as Recordable;

          console.log('flow', list, modelInfo.value.primaryKey, record);

          if (record) {
            const params = record && getRowKeys(modelInfo.value.primaryKey, record);

            const btnData = centerRightBtns.value.find(
              (item) => item.eventType == BTN_EVENT_TYPE.FLOWADD,
            );

            const item = {
              ...btnData,
              moduleId,
              modelId,
              params,
              clearQuery: true,
              record,
            };
            btnItemTemp = item;
            openFlowListSuccess(null);
          }
          console.log('flow', flowData, record);
        }
      } catch (err) {
        console.log('消息跳转后err', err);
      }
    }
  }

  watch(
    () => flowStore.getFlowParams,
    (newVal) => {
      console.log('newVal', newVal);
      const flowData = newVal;
      if (flowData) {
        handleGoToFlow([], flowData);
      }
    },
  );

  onMounted(async () => {
    await init();
  });
  const [registerModal, { openModal, setModalProps }] = useModal();

  const [registerFlowModel, { openModal: openFlowListModal }] = useModal();

  const [registerComFlowModel, { openModal: openComFlowModal }] = useModal();

  const [registerDrawer, { openDrawer, setDrawerProps }] = useDrawer();

  // ---------- 通用弹框查看 start ---------

  // const [registerModal, { openModal: openModalShowModal, closeModal: closeShowModal }] = useModal();

  // ---------- 通用弹框查看 end ---------

  async function init() {
    try {
      loading.value = true;
      const data = await getModuleListInfoApi({ moduleId, modelId });

      modelInfo.value = data.tableDesignInfo;
      const {
        titles,
        pageSize,
        tableButtons,
        checkbox = false,
        tableSetting,
        plainOptions,
      } = data.tableDesignInfo;

      await setSearchForm(titles);

      const columns = await getColumn(titles, plainOptions);
      setComParms(titles, tableButtons);

      setButtons(tableButtons);

      const len = columns.length;
      let scroll = {};
      if (len >= 8) {
        scroll = { x: (len / 8) * 90 + '%' };
      }
      // 是否多选
      let rowSelection: TableRowSelection | undefined = undefined;
      if (checkbox) {
        rowSelection = {
          type: 'checkbox',
        };
      }

      setProps({
        scroll,
        columns,
        api: getList,
        beforeFetch,
        handleSearchInfoFn,
        rowSelection,
        actionColumn: setTableAction(),
        pagination: {
          pageSize,
        },
        showTableSetting: !!tableSetting,
        tableSetting,
        settingSave: saveColumnSort,
      });

      await reload();
    } catch (e) {
      throw e;
    } finally {
      setTimeout(() => {
        loading.value = false;
      }, 0.5 * 1000);
    }
  }

  async function saveColumnSort(plainOptions) {
    const profile = {
      userId: userStore.getUserInfo?.userId,
      moduleId,
      plainOptions,
    };

    // userId
    // moduleId
    await saveUserProfileApi(profile);
    createMessage.success('保存成功');
  }
  function setComParms(titles, tableButtons) {
    titles.forEach((bt) => {
      bt._comParams = comParams.value;
    });
    tableButtons.forEach((bt) => {
      bt.moduleId = moduleId;
      bt._comParams = comParams.value;
    });
  }

  // 列表查询配置
  async function setSearchForm(titles: any[]) {
    const data = titles.filter((el) => el.searchType > 0);

    if (!data.length) {
      return;
    }
    const schemas = await useSearchForm(data, tableFn as any);

    const formConfig: FormProps = {
      schemas,
      compact: false,
      labelWidth: '100%',
      autoSubmitOnEnter: true,
      rowProps: { gutter: 16 },
    };
    setProps({ formConfig, useSearchForm: true });
  }

  // ---------- 按钮配置 start ---------
  const topLeftBtns = ref<any[]>([]);
  const topCenterBtns = ref<any[]>([]);
  const topRightBtns = ref<any[]>([]);
  const centerLeftBtns = ref<any[]>([]);
  const centerRightBtns = ref<any[]>([]);

  const tableItems = computed(() => {
    return [unref(topLeftBtns), unref(topCenterBtns), unref(topRightBtns)];
  });

  const isShowTop = computed(() => {
    return unref(topLeftBtns).length || unref(topCenterBtns).length || unref(topRightBtns).length;
  });

  function setButtons(btns: any[]) {
    // 表格上下按钮位置
    topLeftBtns.value = btns.filter((el) => el.location === BTN_POSITION.TOP_LEFT);
    topCenterBtns.value = btns.filter((el) => el.location === BTN_POSITION.TOP_CENTER);
    topRightBtns.value = btns.filter((el) => el.location === BTN_POSITION.TOP_RIGHT);

    // 表格内部操作按钮
    centerLeftBtns.value = btns.filter((el) => el.location === BTN_POSITION.CENTER_LEFT);
    centerRightBtns.value = btns.filter((el) => el.location === BTN_POSITION.CENTER_RIGHT);
  }

  function setTableAction() {
    const centerRightLen = unref(centerRightBtns).length;

    let col: Indexable | undefined = undefined;
    if (centerRightLen) {
      col = {
        width: 110 * centerRightLen,
        dataIndex: 'rightAction',
        title: '操作',
        fixed: 'right',
      };
    }
    return col;
  }

  function actionsFn(record: Indexable): ActionItem[] {
    const params = {
      ...unref(comParams),
      record,
    };
    const res = useActions(centerRightBtns, params, [
      reload,
      setModalPropsFn,
      openModalFn,
      handleFlowComFn,
    ]);

    return res;
  }

  // ---------- 按钮配置 end ---------

  // 列表接口配置
  let orderby: any[] = [];

  async function getList(data: Indexable = { current: 1, size: 10 }) {
    setLoading(true);
    const params = {
      current: 1,
      size: 10,
      ...data,
      orderby,
      query,
    };

    const ret = await getGetModuleCommonListApi({ moduleId, modelId }, params);

    return ret;
  }

  async function handleChangeSearch(...arg) {
    const sortInfo = arg[2];
    const orderType = {
      ascend: 1,
      descend: 0,
    };

    if (sortInfo.field) {
      const asc = orderType[sortInfo.order];
      const oldSort = orderby.find((el) => el.dataIndex === sortInfo.field);
      if (oldSort) {
        oldSort.asc = asc;
        return;
      } else {
        orderby.push({ dataIndex: sortInfo.field, asc });
      }
    }
  }

  function openFlowListSuccess(id) {
    flowDetailVisible.value = true;
    if (flowDetail.value) {
      console.log('btnItemTemp', btnItemTemp);

      btnItemTemp.templateId = id;
      flowDetail.value?.openPage(true, btnItemTemp);
    }
  }

  // ---------- 通用弹框配置 start ---------

  //----------表格外按钮 start ---------
  async function handleAddFn(btnItem: Indexable) {
    console.log('点击');
    setModalPropsFn(btnItem);
    openModalFn(btnItem);
  }

  // 流程新增
  async function handleFlowAddFn(btnItem: Indexable) {
    btnItemTemp = btnItem;
    openFlowListModal(true, btnItem);
  }

  //流程传阅，征询，转批
  function handleFlowComFn(btnItem: Indexable) {
    const res = getSelectRows();

    const { isUpdate } = btnItem;

    let selectData;

    if (!isUpdate) {
      if (!res.length) {
        createMessage.info('请选择需要操作的数据！');
        return;
      }
      const { isPassArr, isFailArr } = checkFlowFn(res);

      console.log('re2', res, isPassArr, isFailArr);

      // 不是转批没选择数据
      if (btnItem.eventType != BTN_EVENT_TYPE.FLOWTURNBATCH && !isPassArr.length) {
        createMessage.warning(`不可${btnItem.label}`);
        return;
      } else {
        if (res.length > 1) {
          createMessage.warning('不可操作多个');
          return;
        }
      }

      // 转批
      if (btnItem.eventType == BTN_EVENT_TYPE.FLOWTURNBATCH) {
        if (res.length > 1) {
          createMessage.warning('不可操作多个');
          return;
        }

        const flowObj = res[0];
        const flowStatus = Number(flowObj.StateID.value);

        if (flowStatus >= 2) {
          createMessage.warning(`不可${btnItem.label}`);
          return;
        }
      }
      selectData = btnItem.eventType == BTN_EVENT_TYPE.FLOWTURNBATCH ? res : isPassArr;
    }

    console.log('btnItem', btnItem);

    formScheama.value = getBtnFormScheama(btnItem);

    console.log('formScheama.value', formScheama.value);

    openComFlowModal(true, { ...btnItem, isPassArr: selectData });
  }

  // 流程修复
  async function flowRenovateHandler() {
    console.log('流程修复ffg');
    const selectRows = getSelectRows();

    const res = await getSelectRowsFn<Recordable<any>[]>(selectRows);

    console.log('res', res);

    workItemId.value = res && Number(res.map((item) => item.WorkItemID).join());
    flowRenovatePageVisible.value = true;
  }

  // 流程撤回
  async function flowRevocationHandler() {
    const selectRows = getSelectRows();

    await getRecallWorkItemFn(selectRows, reload);
  }

  //----------表格外按钮 end ---------

  function setModalPropsFn(btnItem) {
    const { width: w, placement } = btnItem;
    let width = getCSSValue(w, '60%');

    switch (btnItem.dialogType) {
      case DIALOG_TYPE.drawer:
        setDrawerProps({
          width: width || '50%',
          destroyOnClose: true,
          placement: placement || 'right',
        });
        break;
      case DIALOG_TYPE.modal:
        setModalProps({ width: width || '50%', destroyOnClose: true });
        break;
    }
  }

  //表格内按钮
  function openModalFn(btnItem: Indexable) {
    console.log('打开页面', btnItem);
    // switch (btnItem.businessType) {
    //   case BTN_EVENT_TYPE.SHOW:
    //     openFlowChatReview(true, btnItem);
    //     return;
    // }

    btnItemTemp = btnItem;

    switch (btnItem.dialogType) {
      case DIALOG_TYPE.drawer:
        openDrawer(true, btnItem);
        break;
      case DIALOG_TYPE.modal:
        openModal(true, btnItem);
        break;
      default:
        const { record } = btnItem;
        if (record) {
          btnItemTemp.isUpdate = true;
          openFlowListSuccess(null);
        }
    }
  }

  // ---------- 通用弹框配置 end ---------

  async function handleSuccess() {
    getSelectRows().length && clearSelectedRowKeys();
    reload();
  }
</script>
<style lang="less" scoped>
  .basic-model-spin {
    ::v-deep(.ant-spin-container) {
      height: 100%;
    }
  }
</style>
